/**
 * 北京中流科技有限公司 版权所有
 * http://www.chinasoa.com.cn
 */
package cn.com.chinasoa.cms.portlet.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.x4ee.soa.portal.framework.core.ActionConfig;
import com.x4ee.soa.portal.framework.core.ActionFilter;
import com.x4ee.soa.portal.framework.core.BaseRequestFilter;
import com.x4ee.soa.portal.framework.core.FrameworkConfig;

/**
 * @author 刘洋(liuyang@chinasoa.com.cn)
 * 2007-9-11下午03:37:15
 */
public class URIDownActionFilter extends BaseRequestFilter implements
		ActionFilter {
	public String process(ActionRequest actionRequest, ActionResponse actionResponse,
			ActionConfig actionConfig) throws PortletException, IOException {
		String urn = actionRequest.getParameter(FrameworkConfigWraper.FRAMEWORK_URN_URN);
		if(urn!=null){
			//URI Map
			Object uriMapObj = actionRequest.getPortletSession().getAttribute(FrameworkConfigWraper.FRAMEWORK_URI_MAP);
		  	if((uriMapObj!=null)&&(uriMapObj instanceof Map)){
		  		Map uriMap = (Map)uriMapObj;
		  		Object value= uriMap.get(urn);
		  		if((value!=null)&&(value instanceof String)){
		  			String tValue = (String)value;
					File jspDir = FrameworkConfigWraper.getPortletJspDir(actionRequest);
		  			File jspFile = new File(jspDir,tValue);
		  			if((jspFile!=null)&&(jspFile.exists())){
		  				FileInputStream jspFileInput = new FileInputStream(jspFile);
		  				HttpServletResponse portalResponse = FrameworkConfig.getPortalResponse(actionResponse);
		  				if(portalResponse!=null){
		  					portalResponse.setHeader("Cache-Control", "max-age=0; must-revalidate");
		  					portalResponse.setHeader("Content-Type","application/octet-stream;charset=gb2312");
							portalResponse.setHeader("Cache-Control", "max-age=0; must-revalidate");
							portalResponse.addHeader("Content-Disposition", "attachment; filename=" + tValue);
							IOUtils.copy(jspFileInput,portalResponse.getOutputStream());
							jspFileInput.close();
							portalResponse.flushBuffer();
		  				}
		  			}
		  		}
		  	}			
		}
		return FrameworkConfigWraper.DEFAULT;
	}

}
